package cn.ifavor.googleplay.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.view.View;
import cn.ifavor.googleplay.R;
import cn.ifavor.googleplay.adapter.DefaultAdapter;
import cn.ifavor.googleplay.base.BaseFragment;
import cn.ifavor.googleplay.base.BaseViewHolder;
import cn.ifavor.googleplay.constants.URLConstant;
import cn.ifavor.googleplay.domain.AppInfo;
import cn.ifavor.googleplay.utils.UiUtils;
import cn.ifavor.googleplay.view.BaseListView;

public class SubjectFragment extends BaseFragment {

	private ArrayList<AppInfo> mDatas;

	@Override
	protected View createSuccessView() {
		BaseListView mList = new BaseListView(UiUtils.getContext());
		
		mList.setAdapter(new DefaultAdapter<AppInfo>(mDatas, R.layout.item_subjectinfo, mList){

			@Override
			public void setHolder(BaseViewHolder<AppInfo> holder, AppInfo data) {
				String imageURL = URLConstant.baseURL + "/image?name="+ data.getUrl();
				holder.setImage(R.id.iv_subject, imageURL);
				holder.setText(R.id.tv_subject, data.getDes());				
			}

			@Override
			protected String getUrl(int index) {
				return SubjectFragment.this.getURL(index);
			}

			@Override
			protected List<AppInfo> onParse(String result) {
				parse(result);
				return mDatas;
			}
			
		});
		return mList;
	}

	@Override
	protected String getURL(int index) {
		return URLConstant.baseURL + "/subject?index=" + index;
	}

	@Override
	protected void parse(String result) {
		mDatas = new ArrayList<AppInfo>();
		try {
			 JSONArray array = new JSONArray(result);
			 
			 if (array != null && array.length() > 0){
				 for (int i = 0; i < array.length(); i++) {
					 JSONObject obj2 = array.optJSONObject(i);
					 AppInfo info = new AppInfo(obj2.optString("des"), obj2.optString("url"));
					 
					 mDatas.add(info);
				}
			 }
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void loadCache(String cache) {
		parse(cache);
	}
}
